package com.mind.adjust.task;

import com.alibaba.fastjson2.JSON;
import com.mind.api.WebServiceClient;
import com.mind.cache.lock.annotation.DMLock;
import com.mind.cache.service.CacheService;
import com.mind.common.utils.DateUtils;
import com.mind.common.utils.ExceptionUtil;
import com.mind.common.utils.StringUtils;
import com.mind.customer.mapper.AjTicketTaskMapper;
import com.mind.system.domain.AjTicketTask;
import com.mind.system.domain.vo.ShareCallBackVo;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


import java.util.Date;
import java.util.List;

@Log4j2
@Component
public class CallbackTask {
    @Resource
    private CacheService cacheService;
    @Resource
    private AjTicketTaskMapper ticketTaskMapper;
    @Resource
    private WebServiceClient webServiceClient;

    @Value("${shareCenter.webServiceUrl}")
    private String webServiceUrl;


    @Async
    @DMLock(key = "#task.ticketId")
    public void executeCallbackByTask(AjTicketTask task) {
        AjTicketTask newTask = ticketTaskMapper.selectTicketTaskById(task.getId().longValue());
        int count = 0;
        if (task.getCallbackCount() != null) {
            count = newTask.getCallbackCount();
        }
        int finalCount = count;
        try {

            ticketTaskMapper.updateTicketTask(new AjTicketTask(){{
                setId(newTask.getId());
                setCallbackStatus(3);
            }});
            ShareCallBackVo vo = JSON.parseObject(newTask.getCallbackParams(), ShareCallBackVo.class);
            vo.setDate(DateUtils.getTime());
            webServiceClient.callWebService(webServiceUrl, vo);
            ticketTaskMapper.updateTicketTask(new AjTicketTask() {{
                setId(newTask.getId());
                setCallbackStatus(2);
                setCallbackCount(finalCount + 1);
                setHandelTime(new Date());
                setErrorInfo("");
            }});
        } catch (Exception e) {
            log.error("回调任务{}执行异常", task.getTicketId(), e);
            ticketTaskMapper.updateTicketTask(new AjTicketTask() {{
                setId(newTask.getId());
                setCallbackStatus(1);
                setCallbackCount(finalCount + 1);
                setHandelTime(new Date());
                setErrorInfo(StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000));
            }});
        }
    }

    @Async
    public void executeCallbackTask(Integer callbackStatus) {
        // 异步任务逻辑
        cacheService.setCacheObject("isCallback", true);
        try {
            if (callbackStatus == null) {
                callbackStatus = 1;
            }
            Integer finalCallbackStatus = callbackStatus;
            List<AjTicketTask> ajTicketTasks = ticketTaskMapper.selectTicketTaskList(new AjTicketTask() {{
                setCallbackStatus(finalCallbackStatus);
            }});
            ajTicketTasks.forEach(task -> {
                if (StringUtils.isNotEmpty(task.getCallbackParams())) {
                    int count = 0;
                    if (task.getCallbackCount() != null) {
                        count = task.getCallbackCount();
                    }
                    int finalCount = count;
                    try {
                        ticketTaskMapper.updateTicketTask(new AjTicketTask(){{
                            setId(task.getId());
                            setCallbackStatus(3);
                        }});
                        ShareCallBackVo vo = JSON.parseObject(task.getCallbackParams(), ShareCallBackVo.class);
                        vo.setDate(DateUtils.getTime());
                        webServiceClient.callWebService(webServiceUrl, vo);
                        ticketTaskMapper.updateTicketTask(new AjTicketTask() {{
                            setId(task.getId());
                            setCallbackStatus(2);
                            setCallbackCount(finalCount + 1);
                            setHandelTime(new Date());
                            setErrorInfo("");
                        }});
                    } catch (Exception e) {
                        log.error("回调任务{}执行异常", task.getTicketId(), e);
                        ticketTaskMapper.updateTicketTask(new AjTicketTask() {{
                            setId(task.getId());
                            setCallbackStatus(1);
                            setCallbackCount(finalCount + 1);
                            setHandelTime(new Date());
                            setErrorInfo(StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000));
                        }});
                    }
                }

            });
            //失败
        } catch (Exception e) {
            log.error("回调任务执行异常", e);
        } finally {
            cacheService.deleteObject("isCallback");
        }
    }
}
